package pool
import (
	"context"
	"fmt"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"go.mongodb.org/mongo-driver/mongo/readpref"
	"time"
)
func ReisterMgoPool(poolName string, url string, params ...int) (err error){
	// factory 方法
	factory := func () (interface{}, error) {
		return mongo.Connect(context.Background(), options.Client().ApplyURI(url))
	}

	// close 方法
	close := func (v interface{}) error {
		return v.(*mongo.Client).Disconnect(context.Background())
	}

	// ping 方法
	ping := func (v interface{}) error {
		return v.(*mongo.Client).Ping(context.Background(), readpref.Primary())
	}

	var (
		size int = 5
		cap int = 20
		idle time.Duration = 30
	)

	// 参数覆盖
	for i, v := range params {
		switch i {
		case 0 :
			size = v
		case 1 :
			cap = v
		case 2 :
			idle = time.Duration(v)
		}
	}

	poolConfig := &Config{
		InitialCap: size,
		MaxCap: cap,
		Factory: factory,
		Close: close,
		Ping: ping,
		IdleTimeout: idle * time.Second,
	}

	mgoPool, err := NewChannelPool(poolConfig)

	if !globalPolls.add(poolName, mgoPool) {
		return fmt.Errorf("添加连接池错误")
	}
	return
}

func GetMgoClient(poolName string) (c *mongo.Client, err error){
	if p, ok := globalPolls.get(poolName); ok {
		if v, err := p.Get(); err == nil {
			return v.(*mongo.Client), nil
		}
		return nil, fmt.Errorf("未获取到连接")
	}
	return nil, fmt.Errorf("连接池已关闭")
}

func PutMgoClient(poolName string, c *mongo.Client) (err error) {
	if p, ok := globalPolls.get(poolName); ok {
		err = p.Put(c)
		return
	}
	return fmt.Errorf("连接池已关闭")
}